package com.kunbo.encode.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.kunbo.encode.dao.EncodeDao;
import com.kunbo.encode.dao.EncodeTemplateDao;
import com.kunbo.encode.entity.Encode;
import com.kunbo.encode.entity.EncodeTemplate;
import com.kunbo.encode.service.EncodeService;
import com.shuohe.util.date.SDate;
import com.shuohe.util.string.QString;

@Service
public class EncodeServiceImpl implements EncodeService{

	@Autowired JdbcTemplate jdbcTemplate;
	
	@Autowired EncodeTemplateDao encodeTemplateDao;
	@Autowired EncodeDao encodeDao;
	
	
	@Override
	public List<Encode> getLastEncodeByTemplateIdAndDate(String templateId) {
		
		//判断productId是否为空
		if(QString.isNull(templateId)) return null;
		
		String day = SDate.getSystemDateYMDToString();		
		String start = day+" 00:00:00";  
	    String end = day+" 23:59:59";  
		
		String sql1 = "";
		sql1 += " SELECT";
		sql1 += " 	*";
		sql1 += " FROM";
		sql1 += " 	db_offer_encode_encode";
		sql1 += " WHERE";
		sql1 += " 	db_offer_encode_encode.templateId = '"+templateId+"'";
		sql1 += "   and db_offer_encode_encode.date >='" +start+"' and db_offer_encode_encode.date <='"+end+"'";

		List<Encode> pp_list = jdbcTemplate.query(sql1, new RowMapper<Encode>() {
			@Override
			public Encode mapRow(ResultSet rs, int rowNum) throws SQLException {
				Encode encode = new Encode();
				encode.setDate(rs.getDate("date"));
				encode.setId(rs.getString("id"));
				encode.setNo(rs.getString("no"));
				encode.setTemplateId(rs.getString("templateId"));		
				return encode;
			}
		});
		return pp_list;
	}

	@Override
	public Encode getCode(String templateName) {
		//1、获取模板的信息
		EncodeTemplate encodeTemplate = encodeTemplateDao.findByTemplateName(templateName);
		List<Encode> l = getLastEncodeByTemplateIdAndDate(encodeTemplate.getId());
		
		int length = l.size();
		length++;
		String xs=String.valueOf(length);
		String [] ss = {"0000","000","00","0",""};
		xs = ss[xs.length()+1] + xs;
		String no = SDate.getSystemDateYMD2ToString()+"-"+xs;
		
		Encode e = new Encode();
		e.setTemplateId(encodeTemplate.getId());
		e.setNo(no);
		e.setDate(SDate.getSystemDate());
		encodeDao.save(e);
		
		return e;
	}

}
